const gulp = require('gulp')
const pump = require('pump')
const removeEmptyLines = require('gulp-remove-empty-lines')
const path = require('path')
const fs = require('fs')

const {
  sourceFileName,
  destDir,
  fcss,
  fwxss
} = require('./common')
const {
  decorator
} = require('../config')

// 生成微信小程序样式文件
function generateWxss(cb) {
  const useRpx = (decorator && decorator.rpx) || false
  const ratio = (decorator && +decorator.rem2rpx) || 37.5
  const dotEscape = (decorator && decorator.escape && decorator.escape.dot) || 'd'
  const slashEscape = (decorator && decorator.escape && decorator.escape.slash) || 's'

  const sourceFileContent = fs.readFileSync(
    path.join(destDir, fcss(sourceFileName)
  ), { encoding: 'utf-8' })

  if (!sourceFileContent) {
    return cb()
  }

  let wxssContent = ''

  wxssContent = sourceFileContent.split('\n.')

  for (let i = 0; i < wxssContent.length; i++) {
    if (wxssContent[i] && useRpx) {
      wxssContent[i] = wxssContent[i].replace(/(?<=\:\s*)([\d\.\-])+(?=rem{1})/g, num => num && +num * ratio)
      wxssContent[i] = wxssContent[i].replaceAll('rem', 'rpx')

      wxssContent[i] = wxssContent[i].replaceAll('\\.', dotEscape)
      wxssContent[i] = wxssContent[i].replaceAll('\\/', slashEscape)
    }
  }

  wxssContent = wxssContent.join('\n.')

  let filePath = path.join(destDir, fwxss(sourceFileName))
  fs.writeFileSync(filePath, wxssContent, {
    flag: 'w'
  })

  pump([
    // 输入文件
    gulp.src(path.join(destDir, fwxss(sourceFileName))),
    // 移除空行
    removeEmptyLines(),
    // 输出目录
    gulp.dest(destDir),
  ], cb)
}

module.exports = {
  generateWxss
}